import React, { useState, useEffect, useRef, useCallback } from 'react';
import ReactECharts from 'echarts-for-react';
import { Modal, Button } from 'antd';
import { SearchOutlined } from '@ant-design/icons';

// 定义数据集接口  
interface DataSet {
    label: string;
    data: number[];
    color?: string; // 线条颜色可选  
}

interface LineChartProps {
    labels: string[];
    datasets: DataSet[];
    xAxisTitle: string; // x 轴标题  
    yAxisTitle: string; // y 轴标题  
    chartTitle: string; // 图表标题  
}

// 随机生成颜色的函数  
const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
};

const LineChart: React.FC<LineChartProps> = ({ labels, datasets, xAxisTitle, yAxisTitle, chartTitle }) => {
    const [visible, setVisible] = useState(false);

    // 引入 ref 来获取图表实例
    const chartRef = useRef<any>(null);

    // 定义图表数据生成函数，使用 useCallback 包裹
    const getChartOption = useCallback(() => {
        const processedDatasets = datasets.map(dataset => ({
            ...dataset,
            color: dataset.color ?? getRandomColor(), // 随机生成颜色  
        }));

        return {
            tooltip: {
                trigger: 'axis',
            },
            legend: {
                data: processedDatasets.map(dataset => dataset.label),
            },
            xAxis: {
                type: 'category',
                data: labels,
                name: xAxisTitle, // 使用传入的 x 轴标题  
            },
            yAxis: {
                type: 'value',
                name: yAxisTitle, // 使用传入的 y 轴标题  
            },
            toolbox: {
                feature: {
                    saveAsImage: {} // 提供图表图片保存功能  
                }
            },
            series: processedDatasets.map(dataset => ({
                name: dataset.label,
                type: 'line',
                data: dataset.data,
                itemStyle: {
                    color: dataset.color, // 使用传入的颜色   
                },
                smooth: true, // 平滑曲线  
            })),
        };
    }, [datasets, labels, xAxisTitle, yAxisTitle]); // 依赖于 props 数据

    // 在组件加载或更新时清空图表并重新设置数据
    useEffect(() => {
        if (chartRef.current) {
            const chartInstance = chartRef.current.getEchartsInstance();
            chartInstance.clear(); // 清空图表
            chartInstance.setOption(getChartOption()); // 设置新的图表数据
        }
    }, [getChartOption]);

    // 切换模态框  
    const showModal = () => {
        setVisible(true);
        // 强制调整尺寸以确保渲染正确  
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
        }, 0);
    };

    const handleCancel = () => {
        setVisible(false);
    };

    return (
        <div style={{ width: '100%', paddingLeft: "10px" }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <Button size="small" type="text" onClick={showModal} shape="circle" icon={<SearchOutlined />} />
                <h3>{chartTitle}</h3>
            </div>
            {/* 主图表 */}
            <ReactECharts
                ref={chartRef}
                option={getChartOption()}
                style={{ width: '100%' }}
            />

            {/* 模态框显示的图表 */}
            <Modal
                forceRender
                title={chartTitle}
                open={visible}
                onCancel={handleCancel}
                footer={null}
                width={"70%"}
            >
                <ReactECharts option={getChartOption()} style={{ width: "100%" }} />
            </Modal>
        </div>
    );
};

export default LineChart;
